const mongoose = require('mongoose');
const bcrypt = require('bcryptjs');

const userSchema = new mongoose.Schema({
  username: {
    type: String,
    required: true,
    unique: true,
    trim: true,
    minlength: 3,
    maxlength: 50
  },
  password: {
    type: String,
    required: true,
    minlength: 6
  },
  email: {
    type: String,
    required: true,
    unique: true,
    trim: true,
    lowercase: true
  },
  role: {
    type: String,
    enum: ['admin', 'user'],
    default: 'user'
  },
  permissions: {
    system: { type: Boolean, default: false },
    file: { type: Boolean, default: false },
    nginx: { type: Boolean, default: false },
    database: { type: Boolean, default: false },
    security: { type: Boolean, default: false },
    task: { type: Boolean, default: false },
    app: { type: Boolean, default: false }
  },
  lastLogin: {
    type: Date,
    default: null
  },
  active: {
    type: Boolean,
    default: true
  },
  createdAt: {
    type: Date,
    default: Date.now
  }
});

// 密码哈希处理
userSchema.pre('save', async function(next) {
  if (!this.isModified('password')) return next();
  
  try {
    const salt = await bcrypt.genSalt(10);
    this.password = await bcrypt.hash(this.password, salt);
    next();
  } catch (error) {
    next(error);
  }
});

// 验证密码方法
userSchema.methods.comparePassword = async function(password) {
  return await bcrypt.compare(password, this.password);
};

// 自动为管理员角色赋予所有权限
userSchema.pre('save', function(next) {
  if (this.role === 'admin') {
    this.permissions = {
      system: true,
      file: true,
      nginx: true,
      database: true,
      security: true,
      task: true,
      app: true
    };
  }
  next();
});

const User = mongoose.model('User', userSchema);

module.exports = User; 